<template>
	<view :style="{height:PhoneInfo.windowHeight + 'px',width:PhoneInfo.windowWidth + 'px'}">
		<mvBar :mysNavConfig="mysNavConfig" @onLeftClick="onLeftClick"></mvBar>
		<u-toast ref="uToast"></u-toast>
		<view class="eqpage">
			<u-form labelPosition="left" :model="equipmentForm" ref="form1">
				<u-form-item label="名称" borderBottom prop="name" ref="item1">
					<u-input border="none" v-model="equipmentForm.name" maxlength="20" placeholder="请输入设备名称">
					</u-input>
				</u-form-item>
				<u-form-item label="类型" prop="typename" borderBottom @click="show = true;hideKeyboard()" ref="item4">
					<u--input v-model="equipmentForm.typename" disabled disabledColor="#ffffff" placeholder="请选择设备类型"
						border="none">
					</u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item label="连续报警次数阈值" labelWidth="130" borderBottom @click="anbormalshow = true;hideKeyboard()"
					prop="AbnormalStraightThresholdname" ref="item5">
					<u-input border="none" v-model="equipmentForm.AbnormalStraightThresholdname" disabled
						disabledColor="#ffffff" placeholder="请选择连续报警次数阈值">
					</u-input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<!-- 设备类型 -->
				<u-picker closeOnClickOverlay :immediateChange='true' @cancel="show = false" @confirm="confirm"
					:show="show" :columns="columns" keyName="name"></u-picker>
				<!-- 连续报警次数阈值 -->
				<u-picker closeOnClickOverlay :immediateChange='true' @cancel="anbormalshow = false"
					@confirm="abnormalconfirm" :show="anbormalshow" :columns="abnormalcolumns"
					keyName="name"></u-picker>
				<u-form-item label="简介" borderBottom prop="description" ref="item2">
					<u--textarea confirmType='done' placeholder="请输入设备简介" v-model="equipmentForm.description"
						maxlength="100" :count="true"></u--textarea>
				</u-form-item>
				<u-form-item label="图片" borderBottom prop="picUrl" ref="item3">
					<u-upload name="picUrl" :fileList="fileList" @delete="deletePic" :previewFullImage="true"
						:maxCount="4">
					</u-upload>
					<view v-show="photoshow">
						<u-button shape='circle' color="linear-gradient(to right, rgb(6, 169, 237), rgb(96, 221, 165))"
							type="success" icon="camera" @click="chooseImg" text="选择图片"></u-button>
					</view>
				</u-form-item>
			</u-form>
			<view style="margin: 10% auto; width: 90%;">
				<u-button shape='circle' color="linear-gradient(to right, rgb(39, 167, 225), rgb(65, 132, 234))"
					type="primary" text="确定" @click="submit"></u-button>
			</view>
		</view>
		<gmy-img-cropper ref="gmyImgCropper" cropperType="ratio" fileType="jpg" imgSrc="" @getImg="getImg">
		</gmy-img-cropper>
	</view>
</template>

<script>
	import gmyImgCropper from "../../components/gmy-img-cropper/gmy-img-cropper.vue"
	export default {
		components: {
			gmyImgCropper
		},
		data() {
			return {
				PhoneInfo: '',
				mysNavConfig: {
					/* 占位开启  */
					navPadding: true,
					/* 背景 */
					bgColor: "#2979FF",
					/* 标题 （屏幕中心居中 两边图标中心居中使用slot center1） */
					navTitle: {
						text: "新增设备",
						color: "#ffffff",
						fontSize: "18px", // px upx rpx
						fontWeight: "500", // 100 - 700
					},
					isCustomFn: true,
					btnType: "type2",
					type2Config: {
						// 左图标
						leftPath: "/static/img/back.png",
						// 右图标
						rightPath: "/static/img/home.png",
						// 圆角
						radius: "40rpx",
					}
				},
				userinfo: '',
				equipmentForm: {
					name: '',
					description: '',
					typename: "",
					typeid: '',
					AbnormalStraightThreshold: 1,
					AbnormalStraightThresholdname: '一次',
				},
				show: false,
				anbormalshow: false,
				photoshow: true,
				columns: [],
				abnormalcolumns: [
					[{
							id: 1,
							name: '一次',
						},
						{
							id: 2,
							name: '两次',
						},
						{
							id: 3,
							name: '三次',
						},
						{
							id: 4,
							name: '四次',
						},
						{
							id: 5,
							name: '五次',
						},
						{
							id: 6,
							name: '六次',
						},
						{
							id: 7,
							name: '七次',
						},
						{
							id: 8,
							name: '八次',
						},
						{
							id: 9,
							name: '九次',
						},
						{
							id: 10,
							name: '十次',
						}
					]
				],
				rules: {
					name: [{
							type: 'string',
							required: true,
							message: '请输入设备名称',
							trigger: ['change', 'blur'],
						},
						{
							min: 2,
							max: 20,
							message: '设备名称不能低于2个字并且不能超过20个字',
							trigger: ['change', 'blur'],
						},
					],
					description: [{
							type: 'string',
							required: true,
							message: '请输入设备简介',
							trigger: ['change', 'blur'],
						},
						{
							type: 'string',
							min: 2,
							max: 100,
							message: '设备简介不能低于2个字并且不能超过100个字',
							trigger: ['change', 'blur'],
						},
					],
					typename: [{
						type: 'string',
						required: true,
						message: '请选择设备类型',
						trigger: ['change', 'blur'],
					}],
					AbnormalStraightThresholdname: [{
						type: 'string',
						required: true,
						message: '请选择连续报警次数阈值',
						trigger: ['change', 'blur'],
					}]
				},
				//预览照片
				fileList: [],
				//上传照片
				uploading: [],
				//设备类型
				equipmenttype: []
			}
		},
		onLoad() {
			this.PhoneInfo = this.$utils.GetPhoneInfo();
			this.userinfo = uni.getStorageSync('userinfo');
			//获取设备类型
			this.getequipmenttype()
		},
		onReady() {
			this.$refs.form1.setRules(this.rules)
		},
		methods: {
			getequipmenttype() {
				uni.request({
					url: getApp().globalData.serverAddress + this.$uri.Uri_getType,
					method: "GET",
					success: (res) => {
						if (res.statusCode !== 200) {
							this.$utils.showToast(this, '服务器错误,请联系技术支持人员!', 'error');
							return
						}
						if (res.data.code == 0) {
							this.columns.push(res.data.data)
						} else {
							this.$utils.showToast(this, res.data.msg, 'error');
						}
					},
					fail: () => {
						this.$utils.showToast(this, '获取设备类型失败!', 'error');
					}
				})
			},
			//返回
			onLeftClick() {
				uni.navigateBack({
					delta: 1
				});
			},
			//隐藏软键盘
			hideKeyboard() {
				uni.hideKeyboard()
			},
			//选择连续报警次数
			abnormalconfirm(e) {
				this.equipmentForm.AbnormalStraightThreshold = e.value[0].id;
				this.equipmentForm.AbnormalStraightThresholdname = e.value[0].name;
				this.anbormalshow = false;
				this.$refs.form1.validateField('AbnormalStraightThresholdname')
			},
			//选择设备类型
			confirm(e) {
				this.equipmentForm.typename = e.value[0].name;
				this.equipmentForm.typeid = e.value[0].equipmentCategoryRealId;
				this.show = false;
				this.$refs.form1.validateField('typename')
			},
			//删除照片
			deletePic(event) {
				this.fileList.splice(event.index, 1)
				this.uploading.splice(event.index, 1)
				if (this.fileList.length !== 4) {
					this.photoshow = true;
				} else {
					this.photoshow = false;
				}
			},
			//选择
			chooseImg() {
				this.$refs.gmyImgCropper.chooseImage();
			},
			//裁剪
			getImg(e) {
				const result = this.uploadFilePromise(e);
				this.fileList.push({
					status: 'success',
					message: '',
					url: e
				})
				if (this.fileList.length !== 4) {
					this.photoshow = true;
				} else {
					this.photoshow = false;
				}
				this.imgCropperShow = false;
			},
			uploadFilePromise(url) {
				//压缩图片质量到百分之10
				uni.compressImage({
					src: url,
					quality: 10,
					success: res => {
						return new Promise((resolve, reject) => {
							let a = uni.uploadFile({
								url: getApp().globalData.serverAddress + this.$uri
									.Uri_Image.replace("{userRealId}", this.userinfo
										.userRealId),
								filePath: res.tempFilePath,
								name: 'file',
								success: (res) => {
									if (res.statusCode !== 200) {
										this.$utils.showToast(this, '服务器错误,请联系技术支持人员!',
											'error');
										return
									}
									setTimeout(() => {
										resolve(res.data.data)
										var obj = JSON.parse(res.data);
										this.uploading.push({
											url: obj.data[0]
										})
									}, 1000)
								}
							});
						})
					}
				})
			},
			//新增设备
			submit() {
				let equipmentAddDto = new Object();
				equipmentAddDto.Name = this.equipmentForm.name;
				equipmentAddDto.EquipmentCategoryRealId = this.equipmentForm.typeid;
				equipmentAddDto.Description = this.equipmentForm.description;
				equipmentAddDto.AbnormalStraightThreshold = this.equipmentForm.AbnormalStraightThreshold;
				equipmentAddDto.PicUrl = '';
				if (this.uploading.length > 0) {
					var arrlis = []
					for (let item of this.uploading) {
						arrlis.push(item.url)
					}
					equipmentAddDto.PicUrl = arrlis.join(",")
				}
				this.$refs.form1.validate().then(res => {
					uni.showLoading({
						title: "创建中...",
						mask: true,
					});
					uni.request({
						url: getApp().globalData.serverAddress + this.$uri.Uri_addEquipment.replace(
							"{userRealId}", this.userinfo.userRealId),
						data: JSON.stringify(equipmentAddDto),
						dataType: "json",
						method: "POST",
						success: (res) => {
							if (res.statusCode !== 200) {
								this.$utils.showToast(this, '服务器错误,请联系技术支持人员!', 'error');
								return
							}
							if (res.data.code == 0) {
								this.$utils.showToast(this, '创建成功！', 'success', 4,
									'/pages/equipmentManage/equipmentList?EQid=' +
									res
									.data.data.equipmentRealId + '&number=0');
							} else {
								this.$utils.showToast(this, res.data.msg, 'error');
							}
						},
						fail: () => {
							this.$utils.showToast(this, '创建失败！', 'error');
						},
						complete: () => {
							uni.hideLoading();
						}
					})
				}).catch(errors => {
					this.$utils.showToast(this, '请填写正确的信息！', 'warning');
				})
			}
		}
	}
</script>

<style lang="scss">
	.u-input__content {
		z-index: 0;
	}

	.u-textarea {
		z-index: 0;
	}

	.u-upload__deletable {
		z-index: 0 !important;
	}
</style>
<style lang="scss" scoped>
	.eqpage {
		width: 90%;
		margin: 8% auto;
		padding: 3% 5%;
		background-color: #ffffff;
		border-radius: 15px;
	}
</style>